package main

import "net/http"

type Routable interface {
	Route(method string, pattern string, handleFunc func(ctx *Context))
}

type Handler interface {
	ServerHTTP(ctx *Context)
	Routable
}
type HandlerBasedMap struct {
	handlers map[string]func(ctx *Context)
}

func (h *HandlerBasedMap) ServerHTTP(ctx *Context) {
	key := h.key(ctx.R.Method, ctx.R.URL.Path)
	if handler, ok := h.handlers[key]; ok {
		handler(NewContext(ctx.W, ctx.R))
	} else {
		ctx.W.WriteHeader(http.StatusNotFound)
		_, err := ctx.W.Write([]byte("Not Found!"))
		if err != nil {
			return
		}
	}
}

func (h *HandlerBasedMap) Route(method string, pattern string, handleFunc func(ctx *Context)) {
	key := h.key(method, pattern)
	h.handlers[key] = handleFunc
}

func (h *HandlerBasedMap) key(method, pattern string) string {
	return method + "#" + pattern
}

var _ Handler = &HandlerBasedMap{}

func NewHandlerBasedOnMap() Handler {
	return &HandlerBasedMap{
		handlers: make(map[string]func(c *Context)),
	}
}
